import Promise from 'bluebird';

import service from '../service/woa';
import CONSTANT from '../constant/woa';
import CCONSTANT from '../constant/common';
import USERCONSTANT from '../constant/user';

const setCurrentWoa = ({ commit }, info = {}) => {
  localStorage.setItem(CCONSTANT.STORAGE_LOCAL_WOA, JSON.stringify(info));
  commit(CONSTANT.WOA_SET_CURRENT_ACCOUNT, info);
};

const getWoaList = ({ commit }, info) => {
  const ret = new Promise((resolve, reject) => {
    const server = service.getWoaList(info).then((list) => {
      commit(USERCONSTANT.GET_PUBLIC_ACCOUNTS_SUCCESS, list);
      commit(CONSTANT.WOA_GET_LIST_SUCCESS, list);
      return resolve(list);
    }, (e) => {
      commit(CONSTANT.WOA_GET_LIST_ERROR, e);
      commit(USERCONSTANT.GET_PUBLIC_ACCOUNTS_ERROR, e);
      return reject(e);
    });
    return server;
  });
  return ret;
};
/* eslint-disable */
const unbindWoa = ({ commit }, info) => {
  const ret = new Promise((resolve, reject) => {
    const server = service.newUnbindWoa(info).then(() => {
      // commit(CONSTANT.WOA_UNBIND_SUCCESS, data);
      return resolve();
    }, (e) => {
      commit(CONSTANT.WOA_UNBIND_ERROR, e);
      return reject(e);
    });
    return server;
  });
  return ret;
};
/* eslint-enable */
const checkAppIdOk = ({ commit }, info) => {
  const ret = new Promise((resolve, reject) => {
    const server = service.checkAppIdOk(info).then((data) => {
      if (data.isAvailable) {
        return resolve();
      }
      commit(CONSTANT.WOA_CHECK_APPID_ERROR);
      return reject();
    }, () => {
      commit(CONSTANT.WOA_CHECK_APPID_ERROR);
      return reject();
    });
    return server;
  });
  return ret;
};

export default {
  getWoaList,
  setCurrentWoa,
  unbindWoa,
  checkAppIdOk,
};
